package com.recycle.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class HttpUtils {
    private static final CloseableHttpClient httpClient = HttpClients.createDefault();

    public static String sendGetRequest(String url) throws IOException {
        HttpGet request = new HttpGet(url);
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            return getResponseString(response);
        }
    }

    public static String sendPostRequest(String url, List<NameValuePair> params) throws IOException {
        HttpPost request = new HttpPost(url);
        if (params != null) {
            request.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        }
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            return getResponseString(response);
        }
    }

    private static String getResponseString(HttpResponse response) throws IOException {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            return EntityUtils.toString(entity, "UTF-8");
        } else {
            return null;
        }
    }
}